package jms;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import util.JMSUtils;
import util.JsonUtil;
import action.Action;
import dto.Protocol;

public class JmsMessageConsumer {
	
	private final static Logger logger = LogManager.getLogger(JmsMessageConsumer.class);
	
	private Connection conn;
	private Session session;
	private MessageConsumer consumer;
	private Action messageAction;
	
	public JmsMessageConsumer(){
		
		try {
			conn = JMSUtils.getInstance().createConnection();
			conn.start();
			session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
			Destination destination = session.createQueue("merchant");
			consumer = session.createConsumer(destination);
		} catch (JMSException e) {
			e.printStackTrace();
		}
		
	}
	
	public void setAction(Action action){
		messageAction = action;
	}
	
	public void consume(){
		try {
			consumer.setMessageListener(new MessageListener() {
				@Override
				public void onMessage(Message message) {
					TextMessage textMessage = (TextMessage) message;
					try {
						logger.info(textMessage.getText());
						Protocol protocol = (Protocol) JsonUtil.toJsonObject(textMessage.getText(), Protocol.class);
						messageAction.action(protocol);
						textMessage.acknowledge();
					} catch (JMSException e) {
						logger.error(e);
					}
				}
			});
		} catch (JMSException e) {
			logger.error(e);
		}
	}
	
	public void close(){
		try {
			consumer.close();
			session.close();
			conn.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
}
